# -*- coding: utf-8 -*-
import os
import sys
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tornado.web
import json
import LoggerDefault
from tornado_swagger.setup import setup_swagger
import tornado.options

from FlagEmbedding import FlagModel
daoqiezui = ["数额特别巨大","入户盗窃","多次盗窃","在医院盗窃病人亲友财物","曾因盗窃受过刑事处罚又实施盗窃","携带凶器盗窃","结伙盗窃","盗窃毒品","盗窃家庭成员的财物","盗窃违禁品","控制未成年人盗窃","扒窃","其他严重情节","夜间盗窃","数额巨大","为吸毒而盗窃","在公共交通工具上盗窃","数额较大","造成公私财产损失","携带管制刀具盗窃","在公共场所盗窃","一年内曾因盗窃受过行政处罚","盗窃信用卡并使用","采用破坏性手段盗窃","无情形情节","流窜盗窃","在医院盗窃病人财物","其他特别严重情节"]
model = FlagModel('E:/study/bge-m3/bge-large-zh-v1.5', 
                  query_instruction_for_retrieval="盗窃罪情形判断",
                  use_fp16=True) 
embeddings_2 = model.encode(sentences_2)

dictModel = {}

def LoadModel():
   # 载入模型
    for child in os.listdir('./model'):
        childfile = os.path.join('./model', child)
# 加载保存模型
        dictModel[child] = kashgari.utils.load_model(childfile)
        # 使用模型进行预测
        #print(dictModel[child].predict_top_k_class(["初始化测试","初始化测试2"],top_k=1))

async def ClassifyRecognitionDoing(input_lines,ModelCode):
    error=""
    result1=[]
    if ModelCode in dictModel:
        if not dictModel[ModelCode].embedding.processor.multi_label:
            rs= dictModel[ModelCode].predict_top_k_class(input_lines)
            for r in rs:
                result2=[]
                result2.append({"name":r["label"],"probnum":str(r["confidence"])});
                for sub in r["candidates"]:
                    result2.append({"name":sub["label"],"probnum":str(sub["confidence"])});
                result1.append(result2)
        else:
            rs= dictModel[ModelCode].predict_top_k_class(input_lines,top_k=100)
            for r in rs:
                result2=[]
                for sub in r["candidates"]:
                    if sub["confidence"]>0.1:
                        result2.append({"name":sub["label"],"probnum":str(sub["confidence"])});
                result1.append(result2)
    else:
        LoggerDefault.logging.info('该模型不存在！'+ModelCode)
        error="模型不存在"
        result1 = False
    if result1:
        res = {'result':{'code':"1", 'message':'success'},'body':{'class':result1}}
        return json.dumps(res)
    else:
        res = {'result': {"code": "0", "message": error}}
        return json.dumps(res)

class ClassifyRecognition(tornado.web.RequestHandler):
        async def post(self):
            """
            ---
            tags:
            - ClassifyRecognition
            summary: 文本分类识别
            description: 文本分类识别
            produces:
            - application/json
            parameters:
            -   in: body
                name: body
                description: 识别内容实体
                required: true
                schema:
                    type: object
                    description: 识别内容实体
                    properties:
                        ModelCode:
                            type: string
                        TestText:
                            type: string
            responses:
            "200":
              description: 返回识别结果
              schema:
                    type: object
                    description: 识别结果实体
                    properties:
                        result:
                            type: object
                            properties:
                                code:
                                    type: string
                                    description: 1成功0失败
                                message:
                                    type: string
                        body:
                            type: object
                            properties:
                                class:
                                    type: object
                                    properties:
                                        name:
                                            type: string
                                            description: 分类结果
                                        probnum:
                                            type: string
                                            description: 分类可信度
            """
            #利用ｒｅｑｕｅｓｔ属性
            #取出客户端提交的ｊｓｏｎ字符串
            jsonbyte = self.request.body
            jsonstr = jsonbyte.decode('utf8')  #解码，二进制转为字符串
            jsonobj = json.loads(jsonstr)  #将字符串转为json对象
            input_lines = jsonobj.get('TestText')#就可以用api取值
            ModelCode = jsonobj.get('ModelCode')
            result = await ClassifyRecognitionDoing(input_lines,ModelCode)
            self.write(result)

class Application(tornado.web.Application):
    _routes = [
        tornado.web.url(r'/ClassifyRecognition', ClassifyRecognition)
    ]

    def __init__(self):
        setup_swagger(self._routes,
                              swagger_url='/swagger',
                              api_base_url="/",
                              description="用于模板展示的API接口事例和说明",
                              title="模板API列表",schemes=["http"])
        super(Application, self).__init__(self._routes)

if __name__ == '__main__':
    LoadModel()
    application=Application()
    application.listen(10084)
    LoggerDefault.logging.info("开始监听10084")
    tornado.ioloop.IOLoop.instance().start()
